package tech.aistar.day09.homework;


/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/3/18 3:09 下午
 */
public class TestStringDemo {
    public static void main(String[] args) {
        String newStr = delByStr("javc javoscript","fdfd");
        System.out.println(newStr);

        String str2 = "aaabbbbssssssoopppppp";
        String str1 = "fdaaafdssssssrwererppppppwere";

        System.out.println(commonStr(str1,str2));

    }

    /**
     *
     * @param str 原始字符串
     * @param delStr 删除的字符串
     */
    public static String delByStr(String str,String delStr) {
        //return str.replace(delStr,"");
        //递归算法
        //1. 一定指定递归出口
        if (!str.contains(delStr)) {
            return str;
        }
        //2. 包含...
        //StringBuilder中StringBuilder delete(int start,int end);
        //将String类型转成StringBuilder类型
        StringBuilder builder = new StringBuilder(str);
        //获取delStr在str中的起始下标
        int startIndex = builder.indexOf(delStr);
        int endIndex = startIndex +delStr.length();
        builder.delete(startIndex, endIndex);
        return delByStr(builder.toString(), delStr);
    }

    public static StringBuilder commonStr(String str1,String str2){
        //str1 = 'aaabbbbssssssoopppppp';
        //str2 = 'fdaaafdssssssrwererppppppwere';
        //判断 - 保证str1的长度<str2的长度
        if(str1.length()>str2.length()){
            String temp = str1;
            str1 = str2;
            str2 = temp;

        }

        //存放我们的公串...
        StringBuilder commonStr = new StringBuilder();

        //定义一个变量,用来表示公串的长度
        int len = 0;

        //遍历的应该短一点的字符串...
        for (int i = 0; i < str1.length(); i++) {
            for (int j = i+1; j <=str1.length(); j++) {
                //截取字符串
                String subStr = str1.substring(i,j);
                //获取当前子串的长度
                int length = subStr.length();
                //考虑subStr是否要放入到commonStr中了
                if(str2.contains(subStr) && length>len){
                    //清空一下commonStr
                    commonStr.delete(0,commonStr.capacity());
                    commonStr.append(subStr+" ");
                    len = length;
                }else if(str2.contains(subStr) && length==len){
                    commonStr.append(subStr+" ");
                }
            }
        }
        return commonStr;
    }
}
